<template>
  <div id="retweet">
    <el-dialog
      id="retweetDialog"
      :showClose="false"
      title="转存"
      :visible.sync="retweetVisibleFun"
      @closed="$emit('retweetVisibleBox', false)"
      width="40%"
    >
      <div>
        <div v-show="isAlive">
          <!--<el-input placeholder="输入关键字进行过滤" class="filter-box" v-model="filterText" clearable></el-input>-->
          <el-tree
            v-show="isAlive"
            :data="dataFile"
            highlight-current
            show-checkbox
            node-key="id"
            :check-strictly="true"
            :default-expanded-keys="idTemp"
            @node-click="handleNodeClick"
            @node-expand="handleNodeExpand"
            ref="tree2"
            :render-content="renderContent"
          ></el-tree>
        </div>
        <el-form
          @submit.native.prevent
          v-if="newFileVisible"
          :rules="rules"
          :model="fileValidateForm"
          ref="addForm"
          label-width="100px"
          class="demo-ruleForm"
          status-icon
        >
          <el-form-item label="新建文件夹" prop="newfile">
            <el-input type="age"  v-model="fileValidateForm.newfile" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addFolder('addForm')">新 建</el-button>
            <el-button @click="resetForm('addForm')">返 回</el-button>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer" v-if="isAlive">
        <el-button @click="$emit('retweetVisibleBox', false) ">取 消</el-button>
        <el-button type="primary" @click="getCheckedKeys()">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
      <span>
        文件夹
        <em style="color: #01b1a2">{{msg}}</em> 中已存在该文件，请选择其他文件夹转存
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: ["retweetPara", "retweetVisibleFun"],
  data() {
    let checkFile = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("文件夹名字不能为空"));
      } else {
        let reg = new RegExp('^[^\\\\\\/:.*?\\"<>| ]+$');
        if (!reg.test(value)) {
          callback(new Error('命名格式不正确 (文件名不能为全空或包含空格及 【/.:*?\\"<>|】)'));
        } else if (value.length > 20) {
          callback(new Error("文件夹名长度超出上限"));
        } else {
          callback();
        }
      }
    };
    return {
      msg: "",
      dialogVisible: false,
      fileValidateForm: {
        newfile: ""
      },
      rules: {
        newfile: [{ validator: checkFile, trigger: "blur" }]
      },
      filterText: "",
      dataFile: [
        {
          id: localStorage.getItem("dirId"),
          dirId: localStorage.getItem("dirId"),
          label: "我的文档",
          children: []
        }
      ],
      idTemp: [localStorage.getItem("dirId")],
      removeNodeTemp: null,
      newFileVisible: false,
      isAlive: true,
      folderTemp: "",
      addFloderKey: ""
    };
  },
  created() {
    this.initFiles();
  },
  watch: {
    filterText(val) {
      console.log(111111, val);
      this.$refs.tree2.filter(val);
    }
  },
  methods: {
    closed() {
      $emit("retweetVisibleBox", false);
    },
    getCheckedKeys() {
      console.log(this.$refs.tree2.getCheckedKeys());
      this.submitRetweet(this.$refs.tree2.getCheckedKeys());
    },
    resetForm(formName) {
      this.folderTemp = "";
      this.isAlive = true;
      this.newFileVisible = false;
      this.$refs[formName].resetFields();
    },
    addFolder(formName) {
      console.log("folderTemp: ", this.folderTemp);
      console.log("this.nodeTemp: ", this.nodeTemp);
      this.$refs[formName].validate(valid => {
        if (valid) {
          let para = {
            dirId: this.folderTemp.id,
            fileType: 1,
            fileName: this.fileValidateForm.newfile
          };
          this.$http.post("/file/mkdir", para).then(res => {
            console.log("addFile", res);
            if (res.status == 200) {
              this.addFloderKey = res.data;
              console.log(222222, this.addFloderKey);
              // this.idTemp.push(this.folderTemp.id)
              console.log("this.idTemp", this.idTemp);
              // this.initFiles()
              // this.handleGetChildNode(this.folderTemp.id, this.folderTemp)
              this.handleNodeClick(this.folderTemp, this.nodeTemp);
              this.isAlive = true;
              this.newFileVisible = false;
              this.$message({
                type: "success",
                message: "新建成功"
              });
            }
          });
        }
      });
    },
    submitRetweet(keys) {
      console.log(222222, this.retweetPara);
      console.log("==keys==", keys);
      let keyArray = [];
      for (let item of keys) {
        keyArray.push(Number(item));
      }
      console.log("==keys==", keyArray);
      let para = {
        fileId: this.retweetPara.id, //共享文件夹ID；
        dirId: keyArray //转存文件夹ID；
      };
      if (keys == false) {
        this.$message({
          message: "请选择文件夹或者新建文件夹",
          type: "info"
        });
      } else {
        if(para.fileId != para.dirId){
          console.log("==para===", para);
          this.$http.post("/share/storage", para).then(res => {
            console.log("/share/storage", res);
            let { status, msg, data } = res;
            if (status === 500 && msg === "已转存") {
              this.dialogVisible = true;
              let existsArr = [];
              this.msg = "";
              data.forEach(v => {
                existsArr.push(v.fileName);
              });
              this.msg = existsArr.join(",");
            } else if (status === 200) {
              this.$message.success("文件转存操作成功！");
              this.$emit("retweetVisibleBox", false);
            }
          });
        }else{
          this.$message.error("请选择除自己以外的文件夹转存")
        }
      }
    },
    appendNode(data, node) {
      console.log("appendNode:", data);
      this.folderTemp = data;
      this.nodeTemp = node;
      this.newFileVisible = true;
      this.isAlive = false;
    },
    remove(node, data) {
      const parent = node.parent;
      const children = parent.data.children || parent.data;
      const index = children.findIndex(d => d.id === data.id);
      children.splice(index, 1);
    },
    renderContent(h, { node, data, store }) {
      return (
        <span class="custom-tree-node">
          <span>{node.label}</span>
          <span>
            <el-button
              size="mini"
              type="text"
              icon="fa fa-plus"
              style="margin-left:10px;"
              on-click={() => this.appendNode(data, node)}
            />
          </span>
        </span>
      );
    },
    // <el-button size="mini" type="text" on-click={ () => this.remove(node, data) }>删除</el-button>
    initFiles() {
      this.$http.get("/file/ls").then(
        res => {
          let { data } = res;
          console.log("initFiles", res.data);
          this.dataFile[0].children = [];
          if (res.status === 200 && data !== null) {
            data.forEach((v, k) => {
              if (v.fileType === 1) {
                this.dataFile[0].children.push({
                  id: v.id,
                  dirId: v.dirId,
                  label: v.fileName,
                  type: v.fileType,
                  children: [{}]
                });
              }
            });
            this.idTemp = [localStorage.getItem("dirId"), this.idTemp];
          }
        },
        err => {
          this.$message({
            message: "网络出错!!",
            type: "error"
          });
          console.log(err);
        }
      );
    },
    handleNodeExpand(data, node, comp) {
      this.removeNodeTemp = node;
      console.log("Expand", data, node);
      if (data.label !== "我的文档") {
        this.handleGetChildNode(data.id);
      } else {
        this.initFiles();
      }
    },
    handleNodeClick(data, node) {
      this.removeNodeTemp = node;
      console.log(data.label);
      //点击我的文档
      if (data.label == "我的文档") {
        this.initFiles();
      } else {
        console.log("handleNodeClick=", node.childNodes);
        this.handleGetChildNode(data.id);
      }
    },
    async handleGetChildNode(id) {
      let nodeBox = await this.$http.post("/file/clickdir", { id: id }).then(
        res => {
          let { data } = res;
          console.log("获取子节点", res);
          if (data !== null) {
            let tempInfo = [];
            data.forEach(v => {
              // 过滤掉文件数据，并且重新组织数据
              if (v.fileType === 1) {
                tempInfo.push({
                  id: v.id,
                  dirId: v.dirId,
                  label: v.fileName,
                  type: v.fileType,
                  children: [{}]
                });
              }
            });
            console.log("tempInfo", tempInfo);
            // 文件夹不为空
            if (!(tempInfo == false)) {
              //递归查找添加子节点
              !(function getCurrentPart(id, items) {
                let result;
                for (let i in items) {
                  let item = items[i];
                  if (item.id === id) {
                    result = item;
                    result.children = tempInfo;
                    console.log("tempInfo===", tempInfo);
                    break;
                  } else if (item.children) {
                    result = getCurrentPart(id, item.children);
                  }
                }
                console.log("result", result);
                return result;
              })(tempInfo[0].dirId, this.dataFile);
              console.log("dataFile", this.dataFile);
            } else {
              //删除空节点
              console.log("删除空节点", this.removeNodeTemp);
              if (this.removeNodeTemp !== null) {
                this.remove(
                  this.removeNodeTemp.childNodes[0],
                  this.removeNodeTemp.childNodes[0].data
                );
              }
            }
          } else {
            //删除空节点
            console.log("删除空节点", this.removeNodeTemp);
            if (this.removeNodeTemp !== null) {
              this.remove(
                this.removeNodeTemp.childNodes[0],
                this.removeNodeTemp.childNodes[0].data
              );
            }
          }
          console.log("dataFile》》》》", this.dataFile);
          return this.dataFile;
        },
        err => {
          this.$message({
            message: "网络出错!!",
            type: "error"
          });
        }
      );
      console.log("nodeBox:::", nodeBox);
      if (nodeBox !== undefined) {
        if (!(!this.addFloderKey && this.addFloderKey !== "")) {
          let TheNode = this.removeNodeTemp.childNodes.find(element => {
            console.log(this.addFloderKey, element.key);
            return this.addFloderKey == element.key;
          });
          TheNode.isCurrent = true;
          this.removeNodeTemp.expanded = true;
          console.log("TheNode==", TheNode, this.addFloderKey);
        }
      }
    },
    filterNode(value, data) {
      console.log(1, value, 2, data);
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    }
  }
};
</script>

<style lang="scss">
#retweet {
  .el-dialog__body {
    padding: 20px;
  }
  .filter-box {
    margin-bottom: 10px;
  }
}
</style>

